package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一步交互由三部分构成
 * 1：解析请求
 * 2：处理请求
 * 3：响应客户端
 */
public class ClientHandler implements Runnable {
    private Socket socket;
    public ClientHandler(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //.1解析请求
            HttpRequest httpRequest=new HttpRequest(socket);
            HttpResponse response=new HttpResponse(socket);
            //:2处理请求
           DispatcherServlet dispatcherServlet=new DispatcherServlet();
           dispatcherServlet.service(httpRequest,response);
            //:3发送响应
            response.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //一次http交互后要与客户端断开链接（HTTP协议要求）
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
